using BackOffice.Application.Services;
using Backoffice.Domain.Repositories;
using Backoffice.Domain.Entities.App;
using BackOffice.Application.DTOs;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using BackOffice.Application.Common;

namespace BackOffice.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ArticleController : ControllerBase
    {
        private readonly IArticleService _articleService;
        private readonly IRepository<AppArticle> _articleRepo;
        private readonly ILogService _logService;

        public ArticleController(IArticleService articleService, IRepository<AppArticle> articleRepo, ILogService logService)
        {
            _articleService = articleService;
            _articleRepo = articleRepo;
            _logService = logService;
        }

        // 创建文章
        [HttpPost("create")]
        public async Task<IActionResult> Create([FromBody] CreateOrUpdateArticleDto dto)
        {
            try
            {
                var res = await _articleService.CreateArticleAsync(dto);
                
                if (res.Code == 10000)
                {
                    // 记录成功日志
                    await LogHelper.LogInfoAsync(_logService, HttpContext, "创建文章", $"创建文章: {dto.Title}");
                    return Ok(res.Data);
                }
                else
                {
                    // 记录失败日志
                    await LogHelper.LogWarningAsync(_logService, HttpContext, "创建文章失败", $"创建文章失败: {dto.Title} - {res.Msg}");
                    return BadRequest(res);
                }
            }
            catch (Exception ex)
            {
                // 记录错误日志
                await LogHelper.LogErrorAsync(_logService, HttpContext, "创建文章异常", $"创建文章异常: {dto.Title} - {ex.Message}");
                throw;
            }
        }

        // 更新文章
        [HttpPut("update/{id}")]
        public async Task<IActionResult> Update(Guid id, [FromBody] CreateOrUpdateArticleDto dto)
        {
            try
            {
                var res = await _articleService.UpdateArticleAsync(id, dto);
                
                if (res.Code == 10000)
                {
                    // 记录成功日志
                    await LogHelper.LogInfoAsync(_logService, HttpContext, "更新文章", $"更新文章: {dto.Title} (ID: {id})");
                    return Ok(res.Data);
                }
                else
                {
                    // 记录失败日志
                    await LogHelper.LogWarningAsync(_logService, HttpContext, "更新文章失败", $"更新文章失败: {dto.Title} (ID: {id}) - {res.Msg}");
                    return BadRequest(res);
                }
            }
            catch (Exception ex)
            {
                // 记录错误日志
                await LogHelper.LogErrorAsync(_logService, HttpContext, "更新文章异常", $"更新文章异常: {dto.Title} (ID: {id}) - {ex.Message}");
                throw;
            }
        }

        // 删除文章
        [HttpDelete("delete/{id}")]
        public async Task<IActionResult> Delete(Guid id)
        {
            try
            {
                // 先获取文章信息用于日志记录
                var article = await _articleRepo.GetByIdAsync(id);
                var articleTitle = article?.Title ?? "未知文章";
                
                var res = await _articleService.DeleteArticleAsync(id);
                
                if (res.Code == 10000)
                {
                    // 记录成功日志
                    await LogHelper.LogInfoAsync(_logService, HttpContext, "删除文章", $"删除文章: {articleTitle} (ID: {id})");
                    return Ok(res.Data);
                }
                else
                {
                    // 记录失败日志
                    await LogHelper.LogWarningAsync(_logService, HttpContext, "删除文章失败", $"删除文章失败: {articleTitle} (ID: {id}) - {res.Msg}");
                    return BadRequest(res);
                }
            }
            catch (Exception ex)
            {
                // 记录错误日志
                await LogHelper.LogErrorAsync(_logService, HttpContext, "删除文章异常", $"删除文章异常: ID {id} - {ex.Message}");
                throw;
            }
        }

        // 切换文章状态
        [HttpPost("change-status/{id}")]
        public async Task<IActionResult> ChangeStatus(Guid id, [FromBody] ChangeStatusDto dto)
        {
            try
            {
                // 先获取文章信息用于日志记录
                var article = await _articleRepo.GetByIdAsync(id);
                var articleTitle = article?.Title ?? "未知文章";
                var oldStatus = article?.Status.ToString() ?? "未知";
                var newStatus = ((ArticleStatus)dto.Status).ToString();
                
                var res = await _articleService.ChangeStatusAsync(id, (ArticleStatus)dto.Status);
                
                if (res.Code == 10000)
                {
                    // 记录成功日志
                    await LogHelper.LogInfoAsync(_logService, HttpContext, "更改文章状态", $"更改文章状态: {articleTitle} (ID: {id}) - {oldStatus} -> {newStatus}");
                    return Ok(res.Data);
                }
                else
                {
                    // 记录失败日志
                    await LogHelper.LogWarningAsync(_logService, HttpContext, "更改文章状态失败", $"更改文章状态失败: {articleTitle} (ID: {id}) - {res.Msg}");
                    return BadRequest(res);
                }
            }
            catch (Exception ex)
            {
                // 记录错误日志
                await LogHelper.LogErrorAsync(_logService, HttpContext, "更改文章状态异常", $"更改文章状态异常: ID {id} - {ex.Message}");
                throw;
            }
        }

        // 获取文章列表
        [HttpGet("list")]
        public async Task<IActionResult> GetArticles()
        {
            try
            {
                var res = await _articleService.GetArticleListAsync();
                
                if (res.Code == 10000)
                {
                    // 记录查询日志
                    await LogHelper.LogInfoAsync(_logService, HttpContext, "获取文章列表", "获取文章列表成功");
                    return Ok(res.Data);
                }
                else
                {
                    // 记录失败日志
                    await LogHelper.LogWarningAsync(_logService, HttpContext, "获取文章列表失败", $"获取文章列表失败: {res.Msg}");
                    return BadRequest(res);
                }
            }
            catch (Exception ex)
            {
                // 记录错误日志
                await LogHelper.LogErrorAsync(_logService, HttpContext, "获取文章列表异常", $"获取文章列表异常: {ex.Message}");
                throw;
            }
        }

        //查找功能
        [HttpPost("search")]
        public async Task<IActionResult> Search([FromBody] ArticleSearchDto dto)
        {
            try
            {
                var res = await _articleService.SearchArticlesAsync(dto);
                
                if (res.Code == 10000)
                {
                    // 记录搜索日志
                    var searchCriteria = $"标题: {dto.Title ?? "全部"}, 分类: {dto.Category ?? "全部"}, 标签: {dto.Tags ?? "全部"}";
                    await LogHelper.LogInfoAsync(_logService, HttpContext, "搜索文章", $"搜索文章: {searchCriteria}");
                    return Ok(res.Data);
                }
                else
                {
                    // 记录失败日志
                    await LogHelper.LogWarningAsync(_logService, HttpContext, "搜索文章失败", $"搜索文章失败: {res.Msg}");
                    return BadRequest(res);
                }
            }
            catch (Exception ex)
            {
                // 记录错误日志
                await LogHelper.LogErrorAsync(_logService, HttpContext, "搜索文章异常", $"搜索文章异常: {ex.Message}");
                throw;
            }
        }
    }
}